package org.xyf.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class JwtUtils {

    private static final String JWT_SECRET = "xyf1017514544wanttogetrichwanttosavethewordyouknowthat";//不能有非法的UTF-8字符

    private static final long EXP_DURATION = 3600 * 1000L; //1小时


    public static String checkJwtAndGetSub(String jwt){
        SecretKey key = getSigningKey();
        Jws<Claims> claims = Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(jwt);
        return claims.getPayload().getSubject();
    }


    public static String generateToken(String userId) {
        SecretKey key = getSigningKey();
        Date expiration = new Date(System.currentTimeMillis() + EXP_DURATION);
        return Jwts.builder()
                .subject(userId)
                .expiration(expiration)
                .signWith(key)
                .compact();
    }

    private static SecretKey getSigningKey() {
        byte[] keyBytes = JWT_SECRET.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

}
